package com.guiji.text2video.job.task;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.guiji.text2video.common.core.web.domain.AjaxResult;
import com.guiji.text2video.job.controller.AnalysisController;
import com.guiji.text2video.job.domain.Text2videoConfig;
import com.guiji.text2video.job.domain.YoutubeAnalysis;
import com.guiji.text2video.job.domain.YoutubeExeclResult;
import com.guiji.text2video.job.mapper.Text2videoConfigMapper;
import com.guiji.text2video.job.mapper.YoutubeAnalysisMapper;
import com.guiji.text2video.job.mapper.YoutubeExeclResultMapper;
import com.guiji.text2video.job.service.IYoutubeExeclResultService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @date 2022/2/9 10:58
 */
@Component("youtubeAnalysisTask")
public class YoutubeAnalysisTask {
    private static final Logger logger = LoggerFactory.getLogger(YoutubeAnalysisTask.class);

    @Autowired(required = false)
    Text2videoConfigMapper text2videoConfigMapper;
    @Autowired
    YoutubeAnalysisMapper youtubeAnalysisMapper;
    @Autowired
    YoutubeExeclResultMapper youtubeExeclResultMapper;
    public void analysis(Integer period){
        List<Text2videoConfig> text2videoConfigs;
        List<YoutubeAnalysis> youtubeAnalysisList;
        List<HashMap> weekPushDataList;
        try {
            text2videoConfigs = text2videoConfigMapper.selectAll();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time = sdf.format(new Date());
            youtubeAnalysisList = youtubeAnalysisMapper.selectTodayData(period,time);
            weekPushDataList = youtubeAnalysisMapper.weekPushData();
            logger.info("当日已执行统计数量"+youtubeAnalysisList.size());
        } catch (Exception e) {
            logger.info("数据库连接失败");
            return;
        }
        for (Text2videoConfig text2videoConfig:text2videoConfigs) {
            boolean b = true;
            for (YoutubeAnalysis youtubeAnalysis:youtubeAnalysisList) {
                if(text2videoConfig.getBackup1().equals(youtubeAnalysis.getYoutubeAccount())&&ObjectUtil.isEmpty(youtubeAnalysis.getBackup1())){
                    b = false;
                    break;
                }
            }
            if(b==true){
                //开始调接口查询数据
                String channelId = text2videoConfig.getBackup5();
                String updateBy = text2videoConfig.getUpdateBy();
                Date updateTime = text2videoConfig.getUpdateTime();
                if(ObjectUtil.isNull(channelId)||ObjectUtil.isEmpty(channelId)){
                    //如果获取不到id就跳过
                    continue;
                }else {
                    channelId = channelId.replaceAll("https://www\\.youtube\\.com/channel/","");
                }
                String userName = text2videoConfig.getBackup2();
                String youtubeAccount = text2videoConfig.getBackup1();
                Map param = new HashMap<>();
                param.put("channelId",channelId);
                param.put("userName",userName);
                param.put("period",period);
                HttpResponse execute = null;
                YoutubeAnalysis analysis = new YoutubeAnalysis();
                analysis.setPeriod(period);
                analysis.setYoutubeAccount(youtubeAccount);
                analysis.setYoutubeCookie(userName);
                analysis.setChannelId(channelId);
                analysis.setCreateTime(new Date());
                analysis.setUpdateBy(updateBy);
                analysis.setUpdateTime(updateTime);
                //插入周上传统计
                for (HashMap map:weekPushDataList) {
                    if(map.get("backup_1").equals(youtubeAccount)){
                        analysis.setUploadNum(String.valueOf(map.get("total")));
                    }
                }
                try {
                    logger.info(JSONUtil.toJsonStr(analysis));

                    execute = HttpRequest.get("http://44.236.176.10:5556/api/statistics").form(param).timeout(200000).execute();
                } catch (Exception e) {
                    logger.info(youtubeAccount+"超时");
                    analysis.setBackup1("超时");
                    youtubeAnalysisMapper.insertYoutubeAnalysis(analysis);
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException ex) {
                    }
                    continue;
                }
                if(execute.getStatus()==200){
                    String body = execute.body();
                    JSONObject bodyObject = JSONUtil.parseObj(body);
                    JSONObject resultObject = JSONUtil.parseObj(bodyObject.get("result"));
                    String viewCount = (String) resultObject.get("view_count");
                    try {
                        viewCount = String.valueOf(dealNum(viewCount));
                    } catch (Exception e) {
                        logger.info("观看量转换错误");
                    }
                    String viewTime = (String) resultObject.get("view_time");
                    String avgViewTime = (String) resultObject.get("avg_view_time");
                    String cpm = (String) resultObject.get("cpm");
                    String rpm = (String) resultObject.get("rpm");
                    String subscribeNum = (String) resultObject.get("subscribe_num");
                    try {
                        subscribeNum = String.valueOf(dealNum(subscribeNum));
                    } catch (Exception e) {
                        logger.info("subscribeNum转换错误");
                    }
                    String income = (String) resultObject.get("income");
                    analysis.setViewCount(viewCount);
                    analysis.setViewTime(viewTime);
                    analysis.setAvgViewTime(avgViewTime);
                    analysis.setSubscribeNum(subscribeNum);
                    analysis.setCpm(cpm);
                    analysis.setRpm(rpm);
                    analysis.setIncome(income);
                }else {//如果失败，将失败结果存入backup1
                    String body = execute.body();
                    analysis.setBackup1(body);
                }
                youtubeAnalysisMapper.insertYoutubeAnalysis(analysis);
            }
        }

    }

    public int dealNum(String numString){
        Integer integer;
        if(numString.contains("万")){
            numString = numString.replaceAll("万","").replaceAll("\\.","")+"000";
            integer = Integer.valueOf(numString);
            return integer;
        }
        if(numString.contains("K")){
            numString = numString.replaceAll("K","").replaceAll("\\.","")+"00";
            integer = Integer.valueOf(numString);
            return integer;
        }
        if (numString.contains(",")){
            numString = numString.replaceAll(",","");
            integer = Integer.valueOf(numString);
            return integer;
        }
        return Integer.valueOf(numString);
    }

    public void syncData(int period){
        //获取最新一周的账号统计数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(new Date());
        List<YoutubeAnalysis> youtubeAnalysisList = youtubeAnalysisMapper.selectTodayData0(period,time);
        for (YoutubeAnalysis youtubeAnalysis:youtubeAnalysisList) {
            //一个账号的所有维度批量插入
            List<YoutubeExeclResult> list = new ArrayList<>();
            for(int i=0;i<6;i++){
                YoutubeExeclResult youtubeExeclResult = new YoutubeExeclResult();
                youtubeExeclResult.setYoutubeAccount(youtubeAnalysis.getYoutubeAccount());
                youtubeExeclResult.setYoutubeCookie(youtubeAnalysis.getYoutubeCookie());
                youtubeExeclResult.setPeriodTime(youtubeAnalysis.getPeriod().toString());
                youtubeExeclResult.setAccountAdmin(youtubeAnalysis.getCreateBy());
                youtubeExeclResult.setCreateTime(youtubeAnalysis.getCreateTime());
                if(i==0){
                    youtubeExeclResult.setDimension("view_count");
                    youtubeExeclResult.setIndicatorValue(youtubeAnalysis.getViewCount());
                }
                if(i==1){
                    youtubeExeclResult.setDimension("income");
                    youtubeExeclResult.setIndicatorValue(youtubeAnalysis.getIncome());
                }
                if(i==2){
                    youtubeExeclResult.setDimension("subscribe_num");
                    youtubeExeclResult.setIndicatorValue(youtubeAnalysis.getSubscribeNum());
                }
                if(i==3){
                    youtubeExeclResult.setDimension("cpm");
                    youtubeExeclResult.setIndicatorValue(youtubeAnalysis.getCpm());
                }
                if(i==4){
                    youtubeExeclResult.setDimension("upload_num");
                    youtubeExeclResult.setIndicatorValue(youtubeAnalysis.getUploadNum());
                }
                if(i==5){
                    youtubeExeclResult.setDimension("view_time");
                    youtubeExeclResult.setIndicatorValue(youtubeAnalysis.getViewTime());
                }
                list.add(youtubeExeclResult);
            }
            youtubeExeclResultMapper.bulkInsert(list);
        }

    }

    @Autowired
    IYoutubeExeclResultService iYoutubeExeclResultService;

    public void makeExcel(){
        iYoutubeExeclResultService.makeExcel();
    }

    public void syncDataTotal(){
        syncData(365);//目前需要同步0和365的数据,还需要同步7
        syncData(0);
        syncData(7);
    }

}
